﻿using System;
using System.IO;
using System.Linq;
using System.Text;

namespace LD
{
    public class MesHelper
    {
        private static MesHelper instance;
        private static object locker = new object();
        private static object obj = new object();

        public static MesHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                            instance = new MesHelper();
                    }
                }
                return instance;
            }
        }
        private string Start(TB_Product product)
        {
            StringBuilder m_sbUpdateData = new StringBuilder();
            m_sbUpdateData.Append("_{" + "\r\n");
            m_sbUpdateData.Append($"{product.Barcode}@start\r\n");
            m_sbUpdateData.Append("}" + "\r\n");
            LogHelper.Instance.Bali($"【请求】{m_sbUpdateData}");
            string m_sRep = TcpIpService.Instance["Bali"].Send(m_sbUpdateData.ToString()).ToString();
            LogHelper.Instance.Bali($"【返回】{m_sRep}");

            return m_sRep;
        }
        public bool TestStart(TB_Product product)
        {
            if (string.IsNullOrEmpty(Start(product)))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public bool Post(TB_Product product, string a_b)
        {
            bool result = false;
            if (product == null) return true;

            if (!(bool)Cache.GetCache(CONST.MES_SW))
            {
                LogHelper.Instance.Info($"【{a_b}】Insight屏蔽中");
                return true;
            }
            if (string.IsNullOrEmpty(product.Barcode))
            {
                //LogHelper.Instance.Warr($"【{a_b}】Insight上传中检测不到条码");
                return true;
            }
            if (product.ScrewDatas == null)
                product.ScrewDatas = new System.Collections.Generic.List<TB_Screw>();

            if (product.ScrewDatas.Count == 0) return true;

            //ng不上传
            //if (product.ScrewDatas.Where(p => !p.Result).Any())
            //    return true;

            lock (obj)
            {
                CopyCcdImgToBali(product);
                //ScrewData(product, a_b);
                string m_sRep = string.Empty;
                // m_sRep = Start(product);

                //if (string.IsNullOrEmpty(m_sRep))
                //{
                //    LogHelper.Instance.Warr("Insight上传失败");
                //    return result;
                //}
                //if (m_sRep.IndexOf("err") > 0)
                //{
                //    LogHelper.Instance.Warr("Insight上传失败");
                //    return result;
                //}
                var j_pointAttr = Cache.GetCache(CONST.MES_POINTATTR);
                string stationName = Cache.GetCache(CONST.MES_STATIONNAME).ToString();
                string m_sSNPData = $"{product.Barcode}@pdata";
                string m_sSWVsion = "1.0";
                string m_sCT = product.CT + "";

                StringBuilder m_sbData = new StringBuilder();
                m_sbData.Append($"{m_sSNPData}@CT_S@{m_sCT}" + "\r\n");
                if (j_pointAttr != null)
                {
                    var j_pointAttrs = j_pointAttr as string[];
                    for (int i = 0; i < product.ScrewDatas.Count; i++)
                    {
                        //string name = j_pointAttrs[product.ScrewDatas[i].Point - 1];
                        //string strResult = product.ScrewDatas[i].Result ? "OK" : "NG";

                        //m_sbData.Append($"{m_sSNPData}@{name}_PeakTorque@{product.ScrewDatas[i].扭矩Max.ToString("0.0000")}@{product.ScrewDatas[i].Lsl}@{product.ScrewDatas[i].Usl}@kgf.cm" + "\r\n");
                        //m_sbData.Append($"{m_sSNPData}@{name}_ClampTorque@{product.ScrewDatas[i].扭矩.ToString("0.0000")}" + "\r\n");
                        //m_sbData.Append($"{m_sSNPData}@{name}_Angle@{product.ScrewDatas[i].角度}" + "\r\n");
                        //m_sbData.Append($"{product.Barcode}@attr@{name}_Result@{strResult}" + "\r\n");
                    }
                }

                StringBuilder m_sbUpdateData = new StringBuilder();
                m_sbUpdateData.Append("_{" + "\r\n");
                m_sbUpdateData.Append($"{product.Barcode}@start\r\n");
                m_sbUpdateData.Append($"{product.Barcode}@start_time@{product.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}" + "\r\n");
                m_sbUpdateData.Append($"{product.Barcode}@stop_time@{product.EndTime?.ToString("yyyy-MM-dd HH:mm:ss")}" + "\r\n");
                //m_sbUpdateData.Append($"{product.Barcode}@attr@{stationName}" + "\r\n");
                m_sbUpdateData.Append(m_sbData.ToString());
                m_sbUpdateData.Append($"{product.Barcode}@submit@{m_sSWVsion}" + "\r\n");
                m_sbUpdateData.Append("}" + "\r\n");

                LogHelper.Instance.Bali($"【请求】{m_sbUpdateData.ToString()}");
                m_sRep = TcpIpService.Instance["Bali"].Send(m_sbUpdateData.ToString()).ToString();
                LogHelper.Instance.Bali($"【返回】{m_sRep}");
                if (string.IsNullOrEmpty(m_sRep))
                {
                    //LogHelper.Instance.Warr("Insight上传失败");
                    return result;
                }

                if (m_sRep.IndexOf("err") >= 0 || m_sRep.IndexOf("bad") >= 0)
                {
                    //LogHelper.Instance.Warr("Insight上传失败");
                    return result;
                }

                if (m_sRep.IndexOf("ok") >= 0)
                {
                    result = true;
                }
            }

            return result;
        }
        public void UploadImg(string barcode, string imgName, string imgSourcePath)
        {
            if (string.IsNullOrEmpty(barcode) || !(bool)Cache.GetCache(CONST.MES_SW))
                return;
            string imgRoot = Cache.GetCache(CONST.MES_IMGPATH).ToString();
            if (!string.IsNullOrEmpty(imgRoot) && Directory.Exists(imgRoot))
            {
                string imgDir = Path.Combine(imgRoot, barcode);
                if (!Directory.Exists(imgDir))
                    Directory.CreateDirectory(imgDir);
                try
                {
                    File.Copy(imgSourcePath, Path.Combine(imgDir, imgName));

                }
                catch (Exception)
                {
                    LogHelper.Instance.Warr("Insight目录未映射or未维护");
                }
            }
            else
                LogHelper.Instance.Warr("Insight目录未映射or未维护");
        }
        private void CopyCcdImgToBali(TB_Product product)
        {
            string imgRoot = Cache.GetCache(CONST.MES_IMGPATH).ToString();
            if (!string.IsNullOrEmpty(imgRoot) && Directory.Exists(imgRoot))
            {
                string imgDir = Path.Combine(imgRoot, product.Barcode);
                if (!Directory.Exists(imgDir))
                    Directory.CreateDirectory(imgDir);

                CopyImgToBali(product.Barcode, imgDir);
            }
        }
        public void CopyImgToBali(string barcode, string imgDir)
        {
            string rootDir = Cache.GetCache(CONST.CCD_PATH)?.ToString();
            if (!Directory.Exists(rootDir))
            {
                LogHelper.Instance.Warr("CCD图片目录不存在");
                return;
            }
            string[] imgs = Directory.GetFiles(rootDir, barcode + "*", SearchOption.TopDirectoryOnly);
            foreach (var item in imgs)
            {
                FileInfo img = new FileInfo(item);
                if (img.Extension.Equals(".jpg"))
                {
                    img.CopyTo(Path.Combine(imgDir, img.Name));
                    img.Delete();
                }
            }
        }
        public void DeleteCCDImg(string barcode)
        {
            string rootDir = Cache.GetCache(CONST.CCD_PATH)?.ToString();
            if (!Directory.Exists(rootDir))
            {
                LogHelper.Instance.Warr("CCD图片目录不存在");
                return;
            }
            string[] imgs = Directory.GetFiles(rootDir, barcode + "*", SearchOption.TopDirectoryOnly);
            foreach (var item in imgs)
            {
                FileInfo img = new FileInfo(item);
                if (img.Extension.Equals(".jpg"))
                    img.Delete();
            }
        }
    }
}
